# -*- coding: utf-8 -*-
"""
贪吃蛇游戏

使用Pygame实现的基础贪吃蛇游戏，包含以下功能：
1. 蛇的移动与方向控制
2. 食物生成与得分系统
3. 三种速度调节模式（低速/中速/高速）
4. 碰撞检测与游戏结束机制
"""

# 颜色定义
BLUE = (0, 128, 128)  # 背景色
RED = (60, 60, 60)      # 警告文字颜色
GREEN = (0, 255, 255)     # 食物颜色
BLACK = (0, 0, 0)       # 蛇身颜色
BORDER_COLOR = (0, 0, 255)  # 边框颜色
BUTTON_COLOR = (100, 100, 255)  # 按钮默认颜色
BUTTON_HOVER = (50, 50, 200)    # 按钮悬停颜色

# 游戏区域参数
GAME_AREA_Y = 80         # 游戏区域起始Y坐标
GAME_AREA_HEIGHT = 400   # 游戏区域高度

# -*- coding: utf-8 -*-

import pygame
import time
import random

# 初始化游戏
pygame.init()

dis_width = 600
dis_height = 600

dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('贪吃蛇游戏')

# 设置时钟对象
clock = pygame.time.Clock()

# 游戏参数配置
SNAKE_BLOCK = 10    # 蛇身方块尺寸（像素）
INIT_SPEED = 8   # 初始游戏速度（帧率）
snake_speed = INIT_SPEED  # 当前游戏速度

# 字体定义
font_style = pygame.font.SysFont("SimHei", 25)
score_font = pygame.font.SysFont("SimHei", 35)


def display_score(score):
    """
    在屏幕左上角显示当前得分
    :param score: 当前得分（蛇身长度-1）
    """
    value = score_font.render("你的分数: " + str(score), True, BLACK)
    dis.blit(value, [0, 0])


def draw_snake(SNAKE_BLOCK, snake_list):
    """
    绘制蛇身
    :param snake_block: 单个蛇身方块尺寸
    :param snake_list: 蛇身坐标列表
    """
    for x in snake_list:
        pygame.draw.rect(dis, BLACK, [x[0], x[1], SNAKE_BLOCK, SNAKE_BLOCK])


def show_message(msg, color):
    """
    显示居中文本消息
    :param msg: 要显示的文字内容
    :param color: 文字颜色(RGB元组)
    """
    mesg = font_style.render(msg, True, BLACK)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])


def game_loop():
    """
    主游戏循环
    处理游戏逻辑：
    - 用户输入事件处理
    - 蛇身移动与碰撞检测
    - 食物生成与得分计算
    - 游戏速度调节
    """
    global snake_speed  # 声明全局速度变量用于跨函数修改
    snake_speed = INIT_SPEED  # 初始化游戏速度
    game_over = False
    game_close = False

    # 初始位置（居中于游戏区域）
    x1 = dis_width / 2
    y1 = GAME_AREA_Y + GAME_AREA_HEIGHT//2

    # 蛇的初始移动速度
    x1_change = 0
    y1_change = 0

    snake_List = []
    Length_of_snake = 1

    # 食物生成位置（限制在游戏区域内）
    foodx = round(random.randrange(0, dis_width - SNAKE_BLOCK) / 10.0) * 10.0
    foody = round(random.randrange(GAME_AREA_Y, GAME_AREA_Y + GAME_AREA_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0

    while not game_over:
        # 游戏结束处理循环
        while game_close == True:
            dis.fill(BLUE)
            show_message("游戏结束！按 Q-退出 或 C-重新开始", RED)
            display_score(Length_of_snake - 1)
            # 绘制游戏区域边框
            pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y-2, dis_width, 2))
            pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y+GAME_AREA_HEIGHT, dis_width, 2))
            pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y, 2, GAME_AREA_HEIGHT))
            pygame.draw.rect(dis, BORDER_COLOR, (dis_width-2, GAME_AREA_Y, 2, GAME_AREA_HEIGHT))
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()  # 重新开始游戏

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()  # 获取鼠标点击位置坐标
                if slow_btn.collidepoint(mouse_pos):
                    snake_speed = 8
                elif medium_btn.collidepoint(mouse_pos):
                    snake_speed = 14
                elif fast_btn.collidepoint(mouse_pos):
                    snake_speed = 20
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -SNAKE_BLOCK
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = SNAKE_BLOCK
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -SNAKE_BLOCK
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = SNAKE_BLOCK
                    x1_change = 0

        # �ж����Ƿ�ײ���߽�
        if x1 >= dis_width or x1 < 0 or y1 >= (GAME_AREA_Y + GAME_AREA_HEIGHT) or y1 < GAME_AREA_Y:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(BLUE)
        pygame.draw.rect(dis, GREEN, [foodx, foody, SNAKE_BLOCK, SNAKE_BLOCK])
        snake_Head = []
        snake_Head.append(x1)  # 蛇头X坐标
        snake_Head.append(y1)  # 蛇头Y坐标
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]

        # �ж����Ƿ�ײ���Լ�
        for x in snake_List[:-1]:
            if x == snake_Head:  # 检测蛇头与身体碰撞
                game_close = True

        draw_snake(SNAKE_BLOCK, snake_List)
        display_score(Length_of_snake - 1)
        
        # 绘制速度按钮
        button_width = 80
        button_height = 40
        
        # 低速按钮
        slow_btn = pygame.Rect(dis_width-250, 10, button_width, button_height)
        pygame.draw.rect(dis, BUTTON_COLOR, slow_btn)  # 绘制低速按钮
        dis.blit(font_style.render("低速", True, BLACK), (dis_width-245, 15))
        
        # 中速按钮
        medium_btn = pygame.Rect(dis_width-150, 10, button_width, button_height)
        pygame.draw.rect(dis, BUTTON_COLOR, medium_btn)
        dis.blit(font_style.render("中速", True, BLACK), (dis_width-145, 15))
        
        # 高速按钮
        fast_btn = pygame.Rect(dis_width-50, 10, button_width, button_height)
        pygame.draw.rect(dis, BUTTON_COLOR, fast_btn)
        dis.blit(font_style.render("高速", True, BLACK), (dis_width-45, 15))

        # 绘制游戏区域边框
        pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y-2, dis_width, 2))
        pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y+GAME_AREA_HEIGHT, dis_width, 2))
        pygame.draw.rect(dis, BORDER_COLOR, (0, GAME_AREA_Y, 2, GAME_AREA_HEIGHT))
        pygame.draw.rect(dis, BORDER_COLOR, (dis_width-2, GAME_AREA_Y, 2, GAME_AREA_HEIGHT))
        pygame.display.update()

        # �ж����Ƿ�Ե�ʳ��
        if x1 == foodx and y1 == foody:  # 检测吃到食物
            foodx = round(random.randrange(0, dis_width - SNAKE_BLOCK) / 10.0) * 10.0
            foody = round(random.randrange(GAME_AREA_Y, GAME_AREA_Y + GAME_AREA_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
            Length_of_snake += 1

        clock.tick(snake_speed)  # 控制游戏帧率，实现速度调节功能

    pygame.quit()
    quit()


game_loop()